#ifndef H_ECHO
#define H_ECHO
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <arpa/inet.h>

struct sockaddr_in addr;

static int write_all(int sock, char *buf, int len) 
{
   int total = 0;
   int n;
   while (total < len) 
   {
      #ifdef TCP
      n = send(sock, buf + total, len - total, 0);
      #else
      n = sendto(sock, buf + total, len - total, 0, (struct sockaddr*)&addr, sizeof(struct sockaddr_in));
      #endif
      if (n == -1)
         break;
      total += n;
   }
   return (n == -1 ? -1 : total);
}

static int read_all(int sock, char *buf, int len) 
{
   int readed_len = 0;
   int bytes_read = 0;
   while (1) 
   {      
      #ifdef TCP
      bytes_read = recv(sock, buf, len, 0);
      #else
      socklen_t addrlen = sizeof(struct sockaddr_in);
      bytes_read = recvfrom(sock, buf, len, 0, (struct sockaddr*)&addr, &addrlen);
      #endif
      if (bytes_read <= 0)
         break;
      if (strchr(buf, '\0')) 
      {
         readed_len += bytes_read;
         buf += bytes_read;
         break;
      }
      readed_len += bytes_read;
      buf += bytes_read;
   }
   return len;
}
#endif
